package com.englisheveryday.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.englisheveryday.R;
import com.englisheveryday.constants.Constants;
import com.englisheveryday.net.Downloader;
import com.englisheveryday.net.Downloader.OnFileNotExistListener;
import com.englisheveryday.service.ArticleService;
import com.englisheveryday.utils.ActivityManager;
import com.englisheveryday.utils.EnvironmentCheckUtil;
import com.englisheveryday.utils.L;
import com.englisheveryday.utils.StringUtil;
import com.englisheveryday.vo.ArticleVO;
import com.englisheveryday.vo.AudioDownloadVO;

/**
 * <pre>
 *    
 * </pre>
 * @author 马永华
 * @date 2012-10-14 下午6:30:58
 * @version 1.1
 */

public class AudioDownloadActivity extends Activity{

	private LinearLayout articleLayout,articleDownloadLayout;
	private Handler handler;
	private TextView articleText,articledownloadstatus;
	private ExecutorService executor;
	private boolean isAnalysising;
	private Button downloadStartButton,downloadStopButton,audio_back;
	private AudioDownloadVO articleVO;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.audiodownload_activity);
		ActivityManager.add(this);
		setViews();
		setListeners();
		handler = new AnalysisHandler();
		executor = Executors.newCachedThreadPool();
		//判断SD卡状态
		if(!EnvironmentCheckUtil.SDCardCheck()){
			Toast.makeText(this, R.string.sd_status_error,Toast.LENGTH_SHORT).show();
		}
		refresh();
		L.d("oncreate");
	}
	
	private void setViews(){
		articleLayout = (LinearLayout)findViewById(R.id.audiodownload);
		articleText = (TextView)findViewById(R.id.setting_audiodownload);
		articleDownloadLayout = (LinearLayout)findViewById(R.id.download_layout);
		downloadStartButton = (Button)findViewById(R.id.setting_audiodownload_button_start);
		downloadStopButton = (Button)findViewById(R.id.setting_audiodownload_button_stop);
		articledownloadstatus = (TextView)findViewById(R.id.download_status);
		audio_back = (Button)findViewById(R.id.audiodownload_back);
	}
	
	private void setListeners(){
		articleLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isAnalysising){
					Toast.makeText(AudioDownloadActivity.this, R.string.setting_audiodownload_isanalysis, Toast.LENGTH_SHORT).show();
					return;
				}
				articledownloadstatus.setText("("+(articleVO.getHasDownloadCount()>articleVO.getList().size()?articleVO.getList().size():articleVO.getHasDownloadCount())+"/"+articleVO.getList().size()+")");
				if(articleDownloadLayout.getVisibility()!=View.VISIBLE){
					articleDownloadLayout.setVisibility(View.VISIBLE);
				}else if(articleDownloadLayout.getVisibility()==View.VISIBLE){
					articleDownloadLayout.setVisibility(View.GONE);
				}
					
			}
		});
		downloadStartButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isAnalysising){
					Toast.makeText(AudioDownloadActivity.this, R.string.setting_audiodownload_isanalysis, Toast.LENGTH_SHORT).show();
					return;
				}
				if(articleVO.isDownloading()){
					Toast.makeText(AudioDownloadActivity.this, R.string.setting_audiodownload_status_downloading, Toast.LENGTH_SHORT).show();
					return;
				}
				if(articleVO.getToDownloadCount()-articleVO.getList().size()==articleVO.getToDownloadCount()){
					Toast.makeText(AudioDownloadActivity.this, R.string.setting_audiodownload_noneedtodownload, Toast.LENGTH_SHORT).show();
					return;
				}
				if(!EnvironmentCheckUtil.isNetworkAvailable(AudioDownloadActivity.this)){
					Toast.makeText(AudioDownloadActivity.this, R.string.network_status_notavailable, Toast.LENGTH_SHORT).show();
					return;
				}
				//
				v.setEnabled(false);
				downloadStopButton.setEnabled(true);
				articleVO.setBreak(false);
				executor.submit(new AudioDownloadThread_e(articleVO.getList()));
				Toast.makeText(AudioDownloadActivity.this, R.string.setting_audiodownload_button_start_long, Toast.LENGTH_SHORT).show();
			}
		});
		downloadStopButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!articleVO.isDownloading()){
					Toast.makeText(AudioDownloadActivity.this, R.string.setting_audiodownload_status_hasstop, Toast.LENGTH_SHORT).show();
					return;
				}
				downloadStartButton.setEnabled(true);
				v.setEnabled(false);
				articleVO.setBreak(true);
			}
		});
		audio_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AudioDownloadActivity.this.finish();
			}
		});
	}
	
	private void refresh(){
		articleVO = new AudioDownloadVO();
		setButtonStatus();
		executor.submit(new FileAnalysisThread());
	}
	
	private void setButtonStatus(){
		downloadStartButton.setEnabled(true);
		downloadStopButton.setEnabled(false);
	}
	
	class FileAnalysisThread implements Runnable {
		@Override
		public void run() {
			try{
			isAnalysising = true;
			int page = 0;
			int pageSize = 500;
			int toDownloadCount = 0;
			ArticleService bas = new ArticleService(AudioDownloadActivity.this);
			while(true){
				List<ArticleVO> list = bas.load(page*pageSize+"", pageSize+"");
				if(list==null||list.size()==0)
					break;
				for(ArticleVO vo : list){
					if(!StringUtil.isNull(vo.getAudio())){
						toDownloadCount++;
						if(!isExits(Constants.BASEDIR+vo.getAudio())){
							articleVO.getList().add(vo.getAudio());
						}
					}
				}
				page++;
			}
			articleVO.setToDownloadCount(toDownloadCount);
			handler.sendEmptyMessage(Constants.FILEANALYSIS_STATUS_FINISH);
			
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
	}
	
	//判断文件是否存在
	public boolean isExits(String path){
		File f = new File(path);
		return f.exists();
	}
	
	//handler 处理返回结果
	class AnalysisHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case Constants.FILEANALYSIS_STATUS_FINISH : {
				articleText.setText("("+(articleVO.getToDownloadCount()-articleVO.getList().size())+"/"+articleVO.getToDownloadCount()+")");
				isAnalysising = false;
				L.d("分析结束");
			}
			break;
			case Constants.FILENOWNLOAD_STATUS_OVER : {
					refresh();
			}
			break;
		}
			super.handleMessage(msg);
		}
		
	}
	
	//文件下载线程
	class AudioDownloadThread_e implements Runnable {
		
		private List<String> list;
		
		public AudioDownloadThread_e(List<String> tempList){
			this.list = new ArrayList<String>();
			this.list.addAll(tempList);
		}
		
		@Override
		public void run() {
			articleVO.setDownloading(true);
			articleVO.getRetryList().clear();
			Downloader downloader = new Downloader();
			for(String fileName : list){
				if(articleVO.isBreak())
					break;
				downloader.downloadFromUrl(Constants.URL+fileName,Constants.BASEDIR+fileName);
				downloader.setOnFileNotExistListener(new OnFileNotExistListener() {
					@Override
					public void onFileNotExist(String fileName) {
						L.d(fileName+"文件不存在");
					}
				});
			}
			articleVO.setDownloading(false);
			handler.sendEmptyMessage(Constants.FILENOWNLOAD_STATUS_OVER);
			}
		}
}

